import { defineStore } from 'pinia'
import { unref } from 'vue'
import { LocaleDropdownType, LocaleType } from '#types/local'
import { useLocalStorage } from '@hooks/useLocalStorage'
import { LANGMAP, defaultLang } from '@/config'
import zhCN from 'element-plus/es/locale/lang/zh-cn'
import en from 'element-plus/es/locale/lang/en'
const { state: localLang } = useLocalStorage('lang')
const lang = (unref(localLang) || defaultLang) as unknown as LocaleType

interface LangState {
  currentLang: LocaleDropdownType,
  langMap: LocaleDropdownType[]
}

// element-plus 语言列表文件
const elLangMap = {
  [LANGMAP.zhCN]: zhCN,
  [LANGMAP.en]: en
}

const langStore = defineStore('langStore', {
  state: (): LangState => {
    return {
      currentLang: {
        lang: lang,
        elLocale: elLangMap[lang]
      },
      // 多语言
      langMap: [
        {
          lang: LANGMAP.zhCN,
          name: '简体中文'
        },
        {
          lang: LANGMAP.en,
          name: 'English'
        }
      ]
    }
  },
  getters: {
    getCurrentLang() : LocaleDropdownType {
      return this.currentLang
    },
    getLangMap(): LocaleDropdownType[] {
      return this.langMap
    }
  },
  actions: {
    setLang (newLang: LocaleDropdownType) {
      this.currentLang.lang = newLang?.lang
      this.currentLang.elLocale = elLangMap[newLang?.lang]
      useLocalStorage('lang', newLang?.lang)
    }
  }
})

export default langStore
